package com.atguigu.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.constant.RedisConst;
import com.atguigu.entity.UserInfo;
import com.atguigu.result.RetVal;
import com.atguigu.service.UserInfoService;
import com.atguigu.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    //http://api.gmall.com/user/login
    //具体登录的认证逻辑
    @PostMapping("login")
    public RetVal login(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        //1.根据用户账号密码查询用户信息
        UserInfo dbUserInfo = userInfoService.queryUserFromDb(userInfo);
        if (dbUserInfo != null) {
            //2.生成一个toke给前端
            Map<String, Object> retValMap = new HashMap<>();
            String token = UUID.randomUUID().toString();
            retValMap.put("token", token);
            //用户昵称也返回给页面
            String nickName = dbUserInfo.getNickName();
            retValMap.put("nickName", nickName);

            //3.将用户信息返回给前端 放到redis当中
            String userKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
            JSONObject userInfoJson = new JSONObject();
            userInfoJson.put("userId", dbUserInfo.getId());
            userInfoJson.put("loginIp", IpUtil.getIpAddress(request));
            redisTemplate.opsForValue().set(userKey, userInfoJson.toJSONString(), RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return RetVal.ok(retValMap);
        } else {
            return RetVal.fail().message("登录失败");
        }
    }

    //http://api.gmall.com/user/logout
    //退出逻辑
    @GetMapping("logout")
    public RetVal logout(HttpServletRequest request) {
        //页面已经帮我做了删除cookie的事情(Token,UserInfo)
        //后端需要删除redis中的数据
        /**
         * 如果得到token
         *  a.从cookie中
         *  b.从header中拿
         */
//        String token = "";
//        Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            if (cookie.getName().equals("token")) {
//                System.out.println(cookie.getValue());
//                token = cookie.getValue();
//            }
//        }
        String token = request.getHeader("token");
        String userKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.delete(userKey);
        return RetVal.ok();
    }


}
